package com.hursing.tractor.controller;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;

import com.hursing.tractor.GameView;
import com.hursing.tractor.baseview.UIWindow;
import com.hursing.tractor.model.*;

public final class Game extends Stage {
	
	ViewAssistant mViewAssistant = new ViewAssistant();
	Stage[] mStages = {new StartStage(), new DealStage(), new KittyStage(), new PlayStage()};
	int mCurrentStage = -1;
	private static Game mSharedInstance = new Game();
	
	private static final String mPreferenceKey = Game.class.getName();
	private static final String mMasterLRKey = "lr";
	private static final String mMasterTBKey = "bt";
	private static final String mHouseKey = "h";
	private static final String mDeckCountKey = "d";
	private SharedPreferences mPreference;
	
	public static void setupEnv(Context context, View view) {
		boolean shouldStart = UIWindow.instance().androidView() == null;
		GameView gameView = (GameView) view;
		gameView.setDelegate(mSharedInstance.mViewAssistant);
		UIWindow.instance().androidView(view);
		mSharedInstance.mPreference = context.getSharedPreferences(mPreferenceKey, Context.MODE_PRIVATE);
		if (shouldStart) {
			mSharedInstance.start();
		}
	}
	
	static Game instance() {
		return mSharedInstance;
	}
	
	private Game() {		
	}
	
	
	@Override
	void start() {
		mViewAssistant.initViews();
		load();
		nextStage();
	}
	
	@Override
	void pause() {
		mStages[mCurrentStage].pause();
	}

	@Override
	void recover() {
		mStages[mCurrentStage].recover();
	}
	
	Stage currentStage() {
		return mStages[mCurrentStage];
	}
	
	@Override
	protected void nextStage() {
		if ((++mCurrentStage) == mStages.length) {
			mCurrentStage = 0;
			save();
		}
		mStages[mCurrentStage].start();
	}
	
	private void load() {
		GameData.instance()
			.housePosition(mPreference.getInt(mHouseKey, Player.POSITION_BOTTOM))
			.masterLR(mPreference.getInt(mMasterLRKey, Card.NUMBER_2))
			.masterTB(mPreference.getInt(mMasterTBKey, Card.NUMBER_2))
			.deckCount(mPreference.getInt(mDeckCountKey, 2));
	}
	
	private void save() {
//		mPreference.edit().commit();
	}

}
